package com.lly.songhigh.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lly.songhigh.R;
import com.lly.songhigh.adapter.ChartsDetailRecyclerAdapter;
import com.lly.songhigh.adapter.ChartsDownloadAdapter;
import com.lly.songhigh.application.BaseApplication;
import com.lly.songhigh.constant.StringResouce;
import com.lly.songhigh.constant.URL;
import com.lly.songhigh.entity.ChartsDetail;
import com.lly.songhigh.entity.MusicInfo;
import com.lly.songhigh.entity.dao.AddTo;
import com.lly.songhigh.entity.dao.Collection;
import com.lly.songhigh.entity.dao.RecentPlay;
import com.lly.songhigh.eventbus.MyEvent;
import com.lly.songhigh.greendao.DaoSingleton;
import com.lly.songhigh.service.DownloadServices;
import com.lly.songhigh.utils.ChangeUtils;
import com.lly.songhigh.view.PublishSelectPicPopupWindow;
import com.lly.songhigh.volley.StringRequestUtf;
import com.lly.songhigh.volley.VolleySingleton;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import it.sephiroth.android.library.picasso.Picasso;

/**
 * Created by dllo on 15/10/23.
 * 排行榜详情页
 */


public class ChartsDetailActivity extends BaseActivity implements View.OnClickListener, ChartsDetailRecyclerAdapter.OnItemListener, ChartsDetailRecyclerAdapter.OnMenuClickListener {

    private Toolbar chartsDetailToolbar;
    private CollapsingToolbarLayout chartsDetailCollapsingToolbar;
    private TextView songsListShare, songsListCollection, chartsDetailListenCount, chartsDetailDescription,
            pw_collection, pw_download, pw_share, pw_singer, pw_album, pw_song_info, detailTitle;
    private ImageView chartsDetailToolbarBack, chartsDetailImg;
    private int ranklist_id;
    private VolleySingleton volleySingleton;
    private String title, shareUrl, songsListUrl;
    private ChartsDetail.ImageEntity image;
    private RecyclerView chartsDetailRecyclerView;
    private List<ChartsDetail.SongsEntity> songsEntities;
    private ChartsDetail.SongsEntity downloadSongEntity;
    private ChartsDetailRecyclerAdapter adapter;
    private PublishSelectPicPopupWindow menuWindow;
    private RelativeLayout alpha_layout;
    private ChartsDetail chartsDetail;
    private List<MusicInfo> musicInfos;
    private ListView charts_download_listView;
    private AlertDialog.Builder builder;
    private AlertDialog alertDialog;
    private DaoSingleton daoSingleton;
    private ChartsDetail.SongsEntity songsEntity;
    private List<Collection> collections;
    private Context mContext;
    private boolean isCollected = false; // 判断是否被收藏
    private Toast mToast;
    UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share");
    private String path; // 下载路径


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_charts_detail);
        BaseApplication.getInstance().addActivity(this);

        initView();
        chartsDetailToolbarBack.setOnClickListener(this);
        chartsDetailDescription.setVisibility(View.GONE);
        volleySingleton = VolleySingleton.getInstance();
        daoSingleton = DaoSingleton.getInstance();
        initData();
        initShare();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        mToast = Toast.makeText(this, "", Toast.LENGTH_LONG);
        mContext = ChartsDetailActivity.this;
        chartsDetailImg = (ImageView) findViewById(R.id.charts_detail_img);
        chartsDetailToolbar = (Toolbar) findViewById(R.id.detail_toolbar);
        chartsDetailCollapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.detail_collapsing_toolbar);
        songsListCollection = (TextView) findViewById(R.id.songs_list_collection);
        songsListShare = (TextView) findViewById(R.id.songs_list_share);
        detailTitle = (TextView) findViewById(R.id.detail_title);
        songsListShare.setOnClickListener(this);
        songsListCollection.setOnClickListener(this);
        chartsDetailToolbarBack = (ImageView) findViewById(R.id.detail_toolbar_back);
        chartsDetailListenCount = (TextView) findViewById(R.id.detail_listen_count);
        chartsDetailDescription = (TextView) findViewById(R.id.detail_description);
        chartsDetailToolbarBack = (ImageView) findViewById(R.id.detail_toolbar_back);
        chartsDetailListenCount = (TextView) findViewById(R.id.detail_listen_count);
        chartsDetailDescription = (TextView) findViewById(R.id.detail_description);
        chartsDetailToolbarBack = (ImageView) findViewById(R.id.detail_toolbar_back);
        chartsDetailListenCount = (TextView) findViewById(R.id.detail_listen_count);
        chartsDetailDescription = (TextView) findViewById(R.id.detail_description);
        chartsDetailRecyclerView = (RecyclerView) findViewById(R.id.charts_detail_recycler_view);
        // 设置列表布局的方向, 通过布局管理器对象
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        chartsDetailRecyclerView.setLayoutManager(layoutManager);
        chartsDetailToolbarBack.setOnClickListener(this);
        chartsDetailDescription.setVisibility(View.GONE);
        alpha_layout = (RelativeLayout) findViewById(R.id.alpha_layout);
        // 设置ToolBar标题展开时的属性
        chartsDetailCollapsingToolbar.setExpandedTitleTextAppearance(R.style.CollapsingToolbarLayoutText);

    }

    private void initData() {
        Intent intent = getIntent();
        ranklist_id = intent.getIntExtra("ranklist_id", 1);
        //排行榜分享url
        songsListUrl = URL.CHARTS_SHARE + ranklist_id;
        String url = URL.CHARTS_DETAIL_START_URL + ranklist_id + URL.CHARTS_DETAIL_END_URL;
        StringRequestUtf stringRequestUtf = new StringRequestUtf(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                chartsDetail = gson.fromJson(response, ChartsDetail.class);
                title = chartsDetail.getTitle();
                image = chartsDetail.getImage();
                chartsDetailCollapsingToolbar.setTitle(title);
                detailTitle.setText(title);
                songsEntities = chartsDetail.getSongs();
                Picasso.with(ChartsDetailActivity.this).load(image.getPic()).placeholder(R.mipmap.placeholder_detail_radio_ban).error(R.mipmap.placeholder_detail_radio_ban).into(chartsDetailImg);
                adapter = new ChartsDetailRecyclerAdapter(ChartsDetailActivity.this, songsEntities);
                adapter.setOnItemListener(ChartsDetailActivity.this);
                adapter.setOnMenuClickListener(ChartsDetailActivity.this);
                chartsDetailRecyclerView.setAdapter(adapter);
                String num = ChangeUtils.getCount(chartsDetail.getListen_count()); // 将网络拉取试听数量转化为万
                chartsDetailListenCount.setText(num);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(stringRequestUtf);
    }


    /**
     * 判断数据库中是否有此页相关数据, 并改变相应文字
     */
    @Override
    protected void onResume() {
        super.onResume();
        isCollected = daoSingleton.getAddToById(ranklist_id) != null && daoSingleton.getAddToById(ranklist_id).size() > 0;
        if (isCollected)
            songsListCollection.setText(StringResouce.CANCEL_COLLECTION);
        else
            songsListCollection.setText(StringResouce.COLLECTION);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.detail_toolbar_back:
                finish();
                break;
            case R.id.songs_list_share:
                mController.getConfig().removePlatform(SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN);
                //是否只有已登录用户才能打开分享选择页
                mController.openShare(ChartsDetailActivity.this, false);
                share(songsListUrl);
                break;
            case R.id.songs_list_collection:
                if (!isCollected) { // 若没有被收藏, 将单曲收藏到数据库
                    AddTo addTo = new AddTo(chartsDetail.getTitle(), chartsDetail.getImage().getPic(),
                            StringResouce.CHARTS, chartsDetail.getSongs().size(), (int) chartsDetail.getRanklist_id());
                    daoSingleton.getAddToDao().insert(addTo);
                    songsListCollection.setText(StringResouce.CANCEL_COLLECTION);
                    isCollected = true;
                    mToast.setText(StringResouce.COLLECTION_SUCCESS);
                    mToast.show();
                } else { // 若被收藏过, 则将此单曲从数据库中删除
                    daoSingleton.deleteAddToById(ranklist_id);
                    songsListCollection.setText(StringResouce.COLLECTION);
                    mToast.setText(StringResouce.CANCEL_COLLECTION_SUCCESS);
                    isCollected = false;
                    mToast.show();
                }
                break;
        }
    }

    /**
     * 点击行布局时, 将此页所有歌曲信息保存到数组中, 并使用EventBus将数值传到Service中
     *
     * @param songsEntity 点击行返回的歌曲信息
     * @param position    点击行的位置
     */
    @Override
    public void onItemClick(ChartsDetail.SongsEntity songsEntity, int position) {
        if (songsEntity.getUrlList() != null && songsEntity.getUrlList().size() > 0) {
            daoSingleton.getRecentPlayDao().insertOrReplace(new RecentPlay(songsEntity.getName(),
                    songsEntity.getSingerName(), songsEntity.getAlbumName(),
                    StringResouce.RESOUCE_NET, songsEntity.getUrlList().get(0).getUrl(),
                    songsEntity.getAlbumId(), songsEntity.getUrlList().get(0).getDuration(),
                    songsEntity.getSongId()));
            Intent intent = new Intent(ChartsDetailActivity.this, PlayMusicActivity.class);
            musicInfos = new ArrayList<>();
            for (ChartsDetail.SongsEntity entity : songsEntities) { // 通过遍历将可以播放的所有歌曲信息加入到数组中
                if (entity.getUrlList() != null && entity.getUrlList().size() > 0) {
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setUrl(entity.getUrlList().get(0).getUrl());
                    musicInfo.setDuration(entity.getUrlList().get(0).getDuration());
                    musicInfo.setSingerId(entity.getSingerId());
                    musicInfo.setSingerName(entity.getSingerName());
                    musicInfo.setSongId(entity.getSongId());
                    musicInfo.setSongName(entity.getName());
                    musicInfo.setAlbumId(entity.getAlbumId());
                    musicInfo.setAlbum(entity.getAlbumName());
                    musicInfo.setResouce(StringResouce.RESOUCE_NET);
                    musicInfos.add(musicInfo);
                }
            }
            EventBus.getDefault().post(new MyEvent.DeliverData(musicInfos, songsEntity.getName()));
            startActivity(intent);
        } else {
            Toast.makeText(ChartsDetailActivity.this, StringResouce.PLAY_ERROR, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 点击行布局菜单会回调的方法
     *
     * @param songsEntity 点击行布局返回的歌曲信息
     */
    @Override
    public void onMenuClick(ChartsDetail.SongsEntity songsEntity) {
        this.songsEntity = songsEntity;
        alpha_layout.setVisibility(View.VISIBLE); // 一个半透明布局, 使背景变暗
        View view = LayoutInflater.from(this).inflate(R.layout.popup_window, null);
        downloadSongEntity = songsEntity;
        //单曲分享url
        shareUrl = URL.SHARE_SINGLE_START + songsEntity.getSongId() + URL.SHARE_SINGLE_END;
        pw_collection = (TextView) view.findViewById(R.id.pw_collection);
        pw_download = (TextView) view.findViewById(R.id.pw_download);
        pw_share = (TextView) view.findViewById(R.id.pw_share);
        pw_singer = (TextView) view.findViewById(R.id.pw_singer);
        pw_album = (TextView) view.findViewById(R.id.pw_album);
        pw_song_info = (TextView) view.findViewById(R.id.pw_song_info);
        pw_song_info.setText(StringResouce.SONGNAME + songsEntity.getName());
        pw_singer.setText(StringResouce.SINGERNAME + songsEntity.getSingerName());
        if (songsEntity.getAlbumName() != null && !songsEntity.getAlbumName().equals("")) {
            pw_album.setText(StringResouce.ALBUMNAME + songsEntity.getAlbumName());
        }
        // 使用自定义popupwindow加载自定义视图
        menuWindow = new PublishSelectPicPopupWindow(this, itemsOnClick, view, alpha_layout);
        menuWindow.showAtLocation(findViewById(R.id.detail_toolbar_back),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        // 判断数据库中是否有此首歌曲
        collections = daoSingleton.getCollectionById((int) songsEntity.getSongId());
        if (collections.size() > 0 && collections != null)
            pw_collection.setText(StringResouce.CANCEL_COLLECTION);
        else
            pw_collection.setText(StringResouce.COLLECTION);
    }

    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.pw_collection: // 收藏
                    collection();
                    break;
                case R.id.pw_share: // 分享
                    share(shareUrl);
                    break;
                case R.id.pw_download: // 下载
                    download();
                    break;
                case R.id.pw_singer:
                    intentToSinger();
                    break;
                case R.id.pw_album:
                    intentToAlbum();
                    break;
            }
        }
    };

    // 跳转到专辑界面
    private void intentToAlbum() {
        Intent intentToAlbum = new Intent(ChartsDetailActivity.this, SearchAlbumDetialsActivity.class);
        intentToAlbum.putExtra("_url", (int) songsEntity.getAlbumId());
        startActivity(intentToAlbum);
    }

    // 跳转到歌手界面
    private void intentToSinger() {
        Intent intent = new Intent(ChartsDetailActivity.this, SingerDetailActivity.class);
        intent.putExtra("singerId", (int) songsEntity.getSingerId());
        startActivity(intent);
    }

    // 收藏
    private void collection() {
        if (!(collections.size() > 0 && collections != null)) {
            Collection collection = new Collection();
            collection.setSongName(songsEntity.getName());
            collection.setDuration(songsEntity.getUrlList().get(0).getDuration());
            collection.setAlbumId(songsEntity.getAlbumId());
            collection.setAlbum(songsEntity.getAlbumName());
            collection.setPlayUrl(songsEntity.getUrlList().get(0).getUrl());
            collection.setSingerName(songsEntity.getSingerName());
            collection.setSongId(songsEntity.getSongId());
            collection.setResouce(StringResouce.RESOUCE_NET);
            daoSingleton.getCollectionDao().insert(collection);
            Toast.makeText(ChartsDetailActivity.this, StringResouce.COLLECTION_SUCCESS, Toast.LENGTH_LONG).show();
        } else {
            daoSingleton.deleteCollectionById((int) songsEntity.getSongId());
            Toast.makeText(ChartsDetailActivity.this, StringResouce.DELETE_COLLECTION, Toast.LENGTH_LONG).show();
        }
    }

    // 下载
    private void download() {
//        EventBus.getDefault().post(new MyEvent.GetFileName(downloadSongEntity.getName()));
        if (downloadSongEntity.getAuditionList().size() == 0) { // 判断有没有下载资源
            Toast.makeText(ChartsDetailActivity.this, StringResouce.NO_RESOURCES, Toast.LENGTH_SHORT).show();
        } else {
//            SharedPreferencesUtils.putSharePre(ChartsDetailActivity.this, "Download", "SongName",
//                    downloadSongEntity.getName());
            View view = LayoutInflater.from(ChartsDetailActivity.this).inflate(R.layout.activity_charts_download_listview, null);
            charts_download_listView = (ListView) view.findViewById(R.id.charts_download_listView);
            ChartsDownloadAdapter downloadAdapter = new ChartsDownloadAdapter(downloadSongEntity.getAuditionList(), ChartsDetailActivity.this);
            charts_download_listView.setAdapter(downloadAdapter);
            // 弹出下载品质选择框
            builder = new AlertDialog.Builder(ChartsDetailActivity.this);
            builder.setMessage(StringResouce.CHOOSE_QUALITY);
            builder.setView(view);
            alertDialog = builder.create();
            alertDialog.show();
            charts_download_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    startDownloadService(); // 开启下载服务
                    path = downloadSongEntity.getAuditionList().get(position).getUrl();
                    alertDialog.dismiss();
                    Toast.makeText(mContext, StringResouce.START_DOWNLOADING, Toast.LENGTH_LONG).show();
                }
            });
        }
    }

    // 接收下载服务传递过来的消息知道下载服务已开启
    public void onEventMainThread(MyEvent.IsDlding isDlding) {
        if (isDlding.isDownloading()) {
            EventBus.getDefault().post(new MyEvent.DldMessage(downloadSongEntity.getName(), path));
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    // 与下载服务建立连接
    public void startDownloadService() {
        Intent i = new Intent(mContext, DownloadServices.class);
        mContext.startService(i);
    }

    // 初始化分享参数
    private void initShare() {
        UMQQSsoHandler umqqSsoHandler = new UMQQSsoHandler(this, "100424468",
                "c7394704798a158208a74ab60104f0ba");
        umqqSsoHandler.addToSocialSDK();
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, "100424468",
                "c7394704798a158208a74ab60104f0ba");
        qZoneSsoHandler.addToSocialSDK();
    }

    private void share(String url) {
        //是否只有已登录用户才能打开分享选择页
        mController.openShare(ChartsDetailActivity.this, false);
        QQShareContent qqShareContent = new QQShareContent();
        qqShareContent.setShareContent(StringResouce.SHARE_CONTENT);
        qqShareContent.setTitle(StringResouce.SHARE_TITLE);
        qqShareContent.setTargetUrl(url);
        mController.setShareMedia(qqShareContent);
        QZoneShareContent qzone = new QZoneShareContent();
        //设置分享文字
        qzone.setShareContent(StringResouce.SHARE_CONTENT);
        //设置分享内容的标题
        qzone.setTitle(StringResouce.SHARE_TITLE);
        //设置点击消息的跳转URL
        qzone.setTargetUrl(url);
        mController.setShareMedia(qzone);

        SinaShareContent shareContent = new SinaShareContent();
        shareContent.setTitle(StringResouce.SHARE_TITLE);
        shareContent.setShareContent(StringResouce.SHARE_CONTENT + shareUrl);
        mController.setShareMedia(shareContent);
    }

}